package com.tlvip.arithmetic.ch04;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>description：</p>
 * <p>copyright： copyright(C)2016-2099</p>
 * <p>Life is short,we need passion</p>
 * <p>Summary： </p>
 * <p>instructions： </p>
 * Date 1/24/21</p>
 * Author mac
 *
 * @version 1.0
 */
public class SiZeYunSuan {
    public static double calculate(String s) {
        ArrayStack<Double> numStack = new ArrayStack<Double>(20);
        ArrayStack<String> signStack = new ArrayStack<String>(19);
        List<String> stringList = splitFunction(s);
        String ch;
        for (String x : stringList) {
            switch (x) {
                case "+":
                case "-":
                case "*":
                case "/":
                    signStack.push(x);
                    break;
                default:
                    // 先判断符号栈是否空
                    if (signStack.isEmpty()) {
                        numStack.push(Double.valueOf(x));
                    } else {
                        String sign = signStack.pop();
                        if (sign.equals("*")) {
                            Double temp = Double.valueOf(x) * Double.valueOf(numStack.pop());
                            numStack.push(temp);
                        } else if (sign.equals("/")) {
                            Double temp = Double.valueOf(x) * Double.valueOf(numStack.pop());
                            numStack.push(temp);
                        } else {
                            numStack.push(Double.valueOf(x));
                            signStack.push(sign);
                        }
                    }
            }
        }
        Double result = 0D;
        while (!numStack.isEmpty()) {
            String sign = signStack.pop();
            if (null == sign) {
                sign = "+";
            }
            Double temp = numStack.pop();
            if (sign.equals("-")) {
                temp = temp * -1;
            }
            result = result + temp;
        }

        return result;
    }

    private static List<String> splitFunction(String s) {
        char[] cArray = s.toCharArray();
        List<String> list = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        for (char c : cArray) {
            if (c == '+' || c == '-' || c == '*' || c == '/') {
                list.add(sb.toString());
                sb = new StringBuilder();
                list.add(String.valueOf(c));
                continue;
            }
            sb.append(c);
        }
        list.add(sb.toString());
        return list;
    }

    public static void main(String[] args) {
        String s = "1+2*3-49";
        System.out.println(calculate(s));
    }
}
